@model ERP.WorkforceManage.Dtos.TeamDto

@{
    ViewData["Title"] = Model == null ? "新增班组" : "编辑班组";
    bool isEdit = Model != null;
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>@ViewData["Title"]</title>
    <link rel="stylesheet" href="~/layui/css/layui.css">
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>@ViewData["Title"]</h3>
                </div>
                <div class="layui-card-body">
                    <form class="layui-form" lay-filter="teamForm">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">班组编号</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="teamNumber" value="@(Model?.TeamNumber)" 
                                               placeholder="自动生成" autocomplete="off" class="layui-input" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">班组名称 <span style="color: red;">*</span></label>
                                    <div class="layui-input-block">
                                        <input type="text" name="teamName" value="@(Model?.TeamName)" 
                                               placeholder="请输入班组名称" autocomplete="off" class="layui-input" 
                                               lay-verify="required" lay-reqtext="班组名称不能为空">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">班组类型</label>
                                    <div class="layui-input-block">
                                        <select name="teamType" lay-verify="" lay-search="">
                                            <option value="">请选择班组类型</option>
                                            <option value="注塑" @(Model?.TeamType == "注塑" ? "selected" : "")>注塑</option>
                                            <option value="机加工" @(Model?.TeamType == "机加工" ? "selected" : "")>机加工</option>
                                            <option value="组装" @(Model?.TeamType == "组装" ? "selected" : "")>组装</option>
                                            <option value="仓库" @(Model?.TeamType == "仓库" ? "selected" : "")>仓库</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">班组成员</label>
                                    <div class="layui-input-block">
                                        <button type="button" class="layui-btn layui-btn-primary" id="btnSelectMembers">
                                            <i class="layui-icon layui-icon-user"></i> 选择成员
                                        </button>
                                        <span id="memberCount" style="margin-left: 10px; color: #666;">
                                            已选择 <span id="selectedCount">@(Model?.Members?.Count ?? 0)</span> 人
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">描述</label>
                            <div class="layui-input-block">
                                <textarea name="descr" placeholder="请输入描述" class="layui-textarea" rows="3">@(Model?.Descr)</textarea>
                            </div>
                        </div>

                        <!-- 已选择的成员显示区域 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">已选成员</label>
                            <div class="layui-input-block">
                                <div id="selectedMembers" style="min-height: 60px; padding: 10px; border: 1px solid #e6e6e6; border-radius: 2px; background-color: #fafafa;">
                                    @if (Model?.Members?.Any() == true)
                                    {
                                        @foreach (var member in Model.Members)
                                        {
                                            <span class="layui-badge layui-bg-blue member-tag" data-user-id="@member.UserId" style="margin: 2px; cursor: pointer;" title="点击移除">
                                                @(member.UserNickname ?? member.Username)
                                                <i class="layui-icon layui-icon-close" style="margin-left: 5px;"></i>
                                            </span>
                                        }
                                    }
                                    else
                                    {
                                        <span class="layui-text-muted">暂无选择成员</span>
                                    }
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item" style="margin-top: 30px;">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="submit">保存</button>
                                <button type="button" class="layui-btn layui-btn-primary" onclick="parent.layer.closeAll()">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/layui/layui.js"></script>

<script>
    layui.use(['form', 'layer'], function () {
        var form = layui.form;
        var layer = layui.layer;

        var isEdit = @(isEdit ? "true" : "false");
        var editId = @(Model?.Id ?? 0);
        var selectedMemberIds = @Html.Raw(Json.Serialize(Model?.Members?.Select(m => m.UserId).ToList() ?? new List<int>()));

        // 如果是新增，生成班组编号
        if (!isEdit) {
            $.get('/Team/GenerateTeamNumber', function (res) {
                if (res.code === 0) {
                    $('input[name="teamNumber"]').val(res.data);
                }
            });
        }

        // 更新成员计数
        function updateMemberCount() {
            $('#selectedCount').text(selectedMemberIds.length);
        }

        // 移除成员
        $(document).on('click', '.member-tag', function () {
            var userId = parseInt($(this).data('user-id'));
            var index = selectedMemberIds.indexOf(userId);
            if (index > -1) {
                selectedMemberIds.splice(index, 1);
                $(this).remove();
                updateMemberCount();
                
                // 如果没有成员了，显示提示文字
                if (selectedMemberIds.length === 0) {
                    $('#selectedMembers').html('<span class="layui-text-muted">暂无选择成员</span>');
                }
            }
        });

        // 选择成员
        $('#btnSelectMembers').on('click', function () {
            layer.open({
                type: 2,
                title: '选择班组成员',
                area: ['80%', '80%'],
                content: '/Team/UserSelect?selectedIds=' + selectedMemberIds.join(','),
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    var iframeWindow = window[layero.find('iframe')[0]['name']];
                    
                    // 确保iframe已经加载完成
                    if (!iframeWindow || typeof iframeWindow.getSelectedUsers !== 'function') {
                        layer.msg('页面未加载完成，请稍后再试', { icon: 2 });
                        return false;
                    }
                    
                    var selectedUsers = iframeWindow.getSelectedUsers();
                    console.log('选中的用户:', selectedUsers); // 调试信息
                    
                    if (selectedUsers && selectedUsers.length > 0) {
                        selectedMemberIds = selectedUsers.map(function (user) { return user.id; });
                        
                        // 更新显示
                        var html = '';
                        selectedUsers.forEach(function (user) {
                            html += '<span class="layui-badge layui-bg-blue member-tag" data-user-id="' + user.id + '" style="margin: 2px; cursor: pointer;" title="点击移除">';
                            html += (user.userNickname || user.username);
                            html += '<i class="layui-icon layui-icon-close" style="margin-left: 5px;"></i>';
                            html += '</span>';
                        });
                        
                        $('#selectedMembers').html(html);
                        updateMemberCount();
                    } else {
                        selectedMemberIds = [];
                        $('#selectedMembers').html('<span class="layui-text-muted">暂无选择成员</span>');
                        updateMemberCount();
                    }
                    
                    layer.close(index);
                }
            });
        });

        // 监听提交
        form.on('submit(submit)', function (data) {
            var field = data.field;
            
            // 验证必填字段
            if (!field.teamName) {
                layer.msg('请输入班组名称', { icon: 2 });
                return false;
            }
            
            var submitData = {
                teamName: field.teamName,
                teamType: field.teamType || '',
                descr: field.descr || '',
                memberIds: selectedMemberIds
            };

            // 调试信息
            console.log('提交数据:', submitData);

            var url = isEdit ? '/Team/Update?id=' + editId : '/Team/Create';
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(submitData),
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg(isEdit ? '更新成功' : '创建成功', { icon: 1 }, function () {
                            parent.layer.closeAll();
                        });
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                },
                error: function () {
                    layer.msg('操作失败', { icon: 2 });
                }
            });
            
            return false;
        });
    });
</script>
</body>
</html> 